//
//  HttpNetHelper.m
//  Kaagad Peso
//
//  Created by ZhengChengFeng on 2024/10/15.
//

#import "HttpNetHelper.h"

@implementation HttpNetHelper

+ (void)getNetworkHelperForPath:(NSString *)path parameter:(NSMutableDictionary *)parameters onCompleteSuccess:(HttpSuccessBlock)successNetBlock onCompleteFailur:(HttpFailureBlock)failureNetBlock withIsForm:(BOOL)isForm{
    
    NSString *fullPath = path;
    if([path hasPrefix:@"http"])
        fullPath =  path;
    else{
        fullPath = [NSString stringWithFormat:@"%@%@", kBaseUrl, path];
    }
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        
    if (isForm) {
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];//form
    } else {
        manager.requestSerializer = [AFJSONRequestSerializer serializer];//json
    }
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 15.0f;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"image/jpeg",@"text/plain",@"image/png",@"application/octet-stream",@"text/json",@"text/x-vcard",nil];

    fullPath = [fullPath stringByAppendingFormat:@"?mauser=%@&rifles=%@&revolvers=%@&bring=%@&packing=%@&similes=%@&rumoured=%@&seaward=%@",@"ios",kAppVersion,esString([[UIDevice currentDevice] name]),esString([IDFVTools getIDFV]),esString([UIDevice currentDevice].systemVersion),@"appstore-ca",esString([IDFVTools getIDFV]),esString([[NSUserDefaults standardUserDefaults] objectForKey:kCurrentLanguageCode])];
    
    if (!PMStringIsEmpty(esString([CurrentUser mine].sessionKey))) {
        fullPath = [fullPath stringByAppendingFormat:@"&emanation=%@",esString([CurrentUser mine].sessionKey)];
    }
    
    fullPath = [fullPath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        
    [manager GET:fullPath parameters:parameters headers:@{} progress:^(NSProgress * _Nonnull downloadProgress) {

        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            
            if (PMObjectIsEmpty(dic)) {
                [BoxLoadingHelper hideBoxLoading];
                if (successNetBlock) {
                    successNetBlock([NSString getObjectData:responseObject]);
                }
                return;
            }
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
            NSString *jsonStr= [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            
                            
            if (isDictionary(dic) && [dic[@"pineapples"] integerValue] == kExpireCode) {
                [BoxLoadingHelper hideBoxLoading];
                [CurrentUser logoutControllerWithIsTokenExpire:YES];
                return;
            }
    
            if (successNetBlock) {
                successNetBlock(dic);
            }
           

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [BoxLoadingHelper hideBoxLoading];
            if (failureNetBlock) {
                failureNetBlock(error);
            }
        }];
    
}

+ (void)postNetworkHelperForPath:(NSString *)path parameter:(NSMutableDictionary *)parameters onCompleteSuccess:(HttpSuccessBlock)successNetBlock onCompleteFailur:(HttpFailureBlock)failureNetBlock withIsForm:(BOOL)isForm{
    NSString *fullPath = path;
    if([path hasPrefix:@"http"])
        fullPath =  path;
    else{
        fullPath = [NSString stringWithFormat:@"%@%@", kBaseUrl, path];
    }
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        
    if (isForm) {
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];//form
    } else {
        manager.requestSerializer = [AFJSONRequestSerializer serializer];//json
    }
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 15.0f;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"image/jpeg",@"text/plain",@"image/png",@"application/octet-stream",@"text/json",@"text/x-vcard",nil];

    fullPath = [fullPath stringByAppendingFormat:@"?mauser=%@&rifles=%@&revolvers=%@&bring=%@&packing=%@&similes=%@&rumoured=%@&seaward=%@",@"ios",kAppVersion,esString([[UIDevice currentDevice] name]),esString([IDFVTools getIDFV]),esString([UIDevice currentDevice].systemVersion),@"appstore-ca",esString([IDFVTools getIDFV]),esString([[NSUserDefaults standardUserDefaults] objectForKey:kCurrentLanguageCode])];
    
    if (!PMStringIsEmpty(esString([CurrentUser mine].sessionKey))) {
        fullPath = [fullPath stringByAppendingFormat:@"&emanation=%@",esString([CurrentUser mine].sessionKey)];
    }
    
    fullPath = [fullPath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    [manager POST:fullPath parameters:parameters headers:@{} progress:^(NSProgress * _Nonnull uploadProgress) {
                
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
       
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        
        if (PMObjectIsEmpty(dic)) {
            if (successNetBlock) {
                successNetBlock([NSString getObjectData:responseObject]);
            }
            return;
        }
        
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
        
        NSString *jsonStr= [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            
        
        if (isDictionary(dic) && [dic[@"pineapples"] integerValue] == kExpireCode) {
            [BoxLoadingHelper hideBoxLoading];
            [CurrentUser logoutControllerWithIsTokenExpire:YES];
            return;
        }
        if (successNetBlock) {
            successNetBlock(dic);
        }
       
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [BoxLoadingHelper hideBoxLoading];
        if (failureNetBlock) {
            failureNetBlock(error);
        }
    }];
}


+ (void)postUploadPhotoUrl:(NSString *)url params:(NSDictionary *)params imageData:(NSData *)imgData name:(NSString *)name fileName:(NSString *)fileName mimeType:(NSString *)mimeType withProgress:(ProgressBlock)progress success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure{
    
    NSString *fullPath = url;
    if([url hasPrefix:@"http"])
        fullPath =  url;
    else{
        fullPath = [NSString stringWithFormat:@"%@%@", kBaseUrl, url];
    }
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 15;
    [manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
    
    fullPath = [fullPath stringByAppendingFormat:@"?mauser=%@&rifles=%@&revolvers=%@&bring=%@&packing=%@&similes=%@&rumoured=%@&seaward=%@",@"ios",kAppVersion,esString([[UIDevice currentDevice] name]),esString([IDFVTools getIDFV]),esString([UIDevice currentDevice].systemVersion),@"appstore-ca",esString([IDFVTools getIDFV]),esString([[NSUserDefaults standardUserDefaults] objectForKey:kCurrentLanguageCode])];
    
    if (!PMStringIsEmpty(esString([CurrentUser mine].sessionKey))) {
        fullPath = [fullPath stringByAppendingFormat:@"&emanation=%@",esString([CurrentUser mine].sessionKey)];
    }
    
    
    fullPath = [fullPath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    [manager POST:fullPath parameters:params headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:imgData name:name fileName:fileName mimeType:mimeType];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        if (progress) {
            progress(uploadProgress.fractionCompleted);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
    
}



@end


